package org.blogwu.learn.threadLearn.自己实现一个重入锁.使用AQS;

public class MyReentrantLockTest {

    static MyReentrantLock myReentrantLock = new MyReentrantLock();

    // 必须加volatile，否则有可见性问题
    static volatile int i = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                myReentrantLock.lock();
                i++;
                {
                    System.out.println("重入1");
                    myReentrantLock.lock();
                    i++;
                    {
                        System.out.println("重入2");
                        myReentrantLock.lock();
                        i++;
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        myReentrantLock.unlock();
                        System.out.println("退出重入2");
                    }
                    myReentrantLock.unlock();
                    System.out.println("退出重入1");
                }
                myReentrantLock.unlock();
                System.out.println("退出重入0");
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("ccc");
                myReentrantLock.lock();
                System.out.println("ccc2");
                i++;
                myReentrantLock.unlock();
            }
        });
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("i= " + i);
    }
}
